var echatimFloatBall = (function () {
    function init(dragId, onClickHandler) {
        var startEvt, moveEvt, endEvt
        // 判断是否支持触摸事件
        if ('ontouchstart' in window) {
            startEvt = 'touchstart'
            moveEvt = 'touchmove'
            endEvt = 'touchend'
        } else {
            startEvt = 'mousedown'
            moveEvt = 'mousemove'
            endEvt = 'mouseup'
        }
        // 获取元素
        var drag = document.getElementById(dragId)
        drag.style.position = 'fixed'
        drag.style.cursor = 'move'
        // 标记是拖曳还是点击
        var isClick = true
        var disX, disY, left, top, starX, starY

        drag.addEventListener(startEvt, function (e) {
            // 阻止页面的滚动，缩放
            e.preventDefault()
            // 兼容IE浏览器
            var e = e || window.event
            isClick = true
            // 手指按下时的坐标
            starX = e.touches ? e.touches[0].clientX : e.clientX
            starY = e.touches ? e.touches[0].clientY : e.clientY
            // 手指相对于拖动元素左上角的位置
            disX = starX - drag.offsetLeft
            disY = starY - drag.offsetTop
            // 按下之后才监听后续事件
            document.addEventListener(moveEvt, moveFun)
            document.addEventListener(endEvt, endFun)
        })

        function moveFun(e) {
            // 兼容IE浏览器
            var e = e || window.event
            // 防止触摸不灵敏，拖动距离大于20像素就认为不是点击，小于20就认为是点击跳转
            if (
                Math.abs(starX - (e.touches ? e.touches[0].clientX : e.clientX)) > 2 ||
                Math.abs(starY - (e.touches ? e.touches[0].clientY : e.clientY)) > 2
            ) {
                isClick = false
            }
            left = (e.touches ? e.touches[0].clientX : e.clientX) - disX
            top = (e.touches ? e.touches[0].clientY : e.clientY) - disY
            // 限制拖拽的X范围，不能拖出屏幕
            if (left < 0) {
                left = 0
            } else if (left > document.documentElement.clientWidth - drag.offsetWidth) {
                left = document.documentElement.clientWidth - drag.offsetWidth
            }
            // 限制拖拽的Y范围，不能拖出屏幕
            if (top < 0) {
                top = 0
            } else if (top > document.documentElement.clientHeight - drag.offsetHeight) {
                top = document.documentElement.clientHeight - drag.offsetHeight
            }
            drag.style.left = left + 'px'
            drag.style.top = top + 'px'
        }

        function endFun(e) {
            document.removeEventListener(moveEvt, moveFun)
            document.removeEventListener(endEvt, endFun)
            if (isClick){
                if (typeof onClickHandler === 'function') { // 点击
                    onClickHandler();
                }
            }
        }
    }
    function setPosition(dragId, x, y) {
        var drag = document.getElementById(dragId);
        drag.style.position = 'fixed';
        drag.style.left = x + 'px';
        drag.style.top = y + 'px';
    }
    function hide(dragId) {
        var drag = document.getElementById(dragId);
        drag.style.display = 'none';
    }
    function show(dragId) {
        var drag = document.getElementById(dragId);
        drag.style.display = '';
    }
    return {
        init:init,
        hide:hide,
        show:show,
        setPosition:setPosition
    }
})();


var echatimsdkEmber = (function () {
    console.log("echatimsdk-embed init.");
    var iframeId = 'iframe-' + new Date().getTime();
    var ballId = 'ball-' + new Date().getTime();
    // iframe 大小调节
    var resizeConfig = {
        'minimum':[320,640],
        'full':[800,672],
    };


    function resizeIframe(size) {
        var config = resizeConfig[size];
        if(!config){
            return;
        }
        var iframe = document.getElementById(iframeId);
        iframe.width = config[0];
        iframe.height = config[1];

        var bottom = iframe.offsetTop + iframe.offsetHeight;
        var left = iframe.offsetLeft;
        var width = iframe.offsetWidth;
        echatimFloatBall.setPosition(ballId, left + width - 48, bottom + 48);
        echatimFloatBall.show(ballId);
    }

    function createIMIFrame(sdkHost, chatWindowStyle) {
        var iframe = document.createElement("iframe");
        iframe.width = 0;
        iframe.height = 0;
        iframe.id = iframeId;
        iframe.src = sdkHost + '/' + 'app.html?embed=1';
        iframe.style.overflow = 'hidden';
        iframe.style.border = 0;
        iframe.style.position = 'fixed';
        iframe.style.top = '1%';
        iframe.style.right = '5%';
        iframe.style.zIndex = 9;
        for(var v in chatWindowStyle){
            iframe.style[v] = chatWindowStyle[v];
        }
        document.body.appendChild(iframe);
    }
    function createIMFloatBall(ballText, ballStyle) {
        var ball = document.createElement("div");
        ball.id = ballId;
        ball.style.background = '#17a2b8';
        ball.style.color = 'white';
        ball.style.width = '50px';
        ball.style.height = '50px';
        ball.style.height = '50px';
        ball.style.lineHeight = '50px';
        ball.style.borderRadius = '50%';
        ball.style.boxShadow = '5px 5px 40px rgba(0, 0, 0, 0.5)';
        ball.style.transition = 'all 0.08s';
        ball.style.userSelect = 'none';
        ball.style.top = '90%';
        ball.style.right = '10%';
        ball.style.transform = "translate3d(-50%, -50%, 0)";
        ball.style.textAlign = "center";
        ball.style.zIndex = 10;
        ball.innerText = ballText;
        ball.style.display = 'none'; // hide
        for(var v in ballStyle){
            ball.style[v] = ballStyle[v];
        }
        document.body.appendChild(ball);
    }

    function init(config) {
        var sdkHost = config.sdkHost || '';
        var apiKey = config.apiKey || '';
        var sdkKey = config.sdkKey || '';
        var userAuid = config.userAuid || '';
        var userToken = config.userToken || '';
        var ballText = config.ballText || '聊天';
        var chatWindowStyle = config.chatWindowStyle || {};
        var ballStyle = config.ballStyle || {};

        function handlerEasyIMSDKMessage(e) {
            console.log("handlerEasyIMSDKMessage:" + JSON.stringify(e));
            if(sdkHost !== e.origin){
                // console.error(`sdkHost !== e.origin, sdkHost = ${sdkHost}, e.origin:${e.origin}`);
                // return;
            }
            if(!e.data.cmd){
                console.error(`e.data.cmd is empty.`);
                return;
            }
            switch (e.data.cmd) {
                case 'resize':resizeIframe(e.data.extras.size);break;
                case 'hide':document.getElementById(iframeId).style.display = 'none';break;
            }
            console.log("parent app receive:" + JSON.stringify(e.data));
        }

        // 初始化聊天沙盒
        createIMIFrame(sdkHost, chatWindowStyle);
        var iframeInsert = document.getElementById(iframeId);
        window.addEventListener("message",handlerEasyIMSDKMessage,true);
        iframeInsert.onload = function(){
            iframeInsert.contentWindow.postMessage({apiKey: apiKey, cmd:'init', extras:{userAuid:userAuid, userToken:userToken}}, sdkHost)
        };
        // 初始化悬浮球
        createIMFloatBall(ballText, ballStyle);
        echatimFloatBall.init(ballId, function () {
            var display = document.getElementById(iframeId).style.display;
            if(display === ''){
                document.getElementById(iframeId).style.display = 'none'; // hide iframe
            }
            else {
                document.getElementById(iframeId).style.display = ''; // show iframe
            }
        })

    }

    return {
        init:init
    }

})();
